package com.chen.service.Impl;

import com.chen.common.Result;
import com.chen.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author chenchao
 */
@Service
public class MailService {
    public static  String codes;

    @Autowired
    private JavaMailSender mailSender;//一定要用@Autowired

    @Autowired
    private RedisTemplate redisTemplate;


    @Resource
    private UserMapper userMapper;//注入UserMapper，交给bena

    //application.properties中已配置的值
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 给前端输入的邮箱，发送验证码
     * @param email
     * @param
     * @return
     */
    public Result sendMimeMail(String email, String code) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("验证码邮件");//主题
            //生成随机数
             code = randomCode();
             codes=code;

            //将随机数放置到session中
        /*    session.setAttribute("email",email);
            session.setAttribute("code",code);*/

            mailMessage.setText("您收到的验证码是："+code);//内容
            System.out.println(code);
            redisTemplate.opsForValue().set("phone",code,60, TimeUnit.SECONDS);

            mailMessage.setTo(email);//发给谁

            mailMessage.setFrom(from);//你自己的邮箱

            try {
                mailSender.send(mailMessage);//发送
            } catch (MailException e) {
                e.printStackTrace();
            }
            return  Result.success("成功");
        }catch (Exception e){
            e.printStackTrace();
            return  Result.error(20000,"成功");
        }
    }

    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    public String randomCode(){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

}

